package com.example.im.ui.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.im.R
import com.example.im.entity.FriendOrRoom
import com.xlkj.ehobe.storage.ui.adapter.holder.RecyclerViewHolder
import kotlinx.android.synthetic.main.recycler_item_friend_room.view.*


class FriendRoomAdapter(
    private val mContext: Context,
    private val rooms: MutableList<FriendOrRoom>
) :
    RecyclerView.Adapter<RecyclerViewHolder>() {


    private var mOnClickItemListener: OnClickItemListener? = null

    fun setOnItemClickListener(mOnClickItemListener: OnClickItemListener) {
        this.mOnClickItemListener = mOnClickItemListener
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder {
        return RecyclerViewHolder(
            LayoutInflater.from(mContext).inflate(
                R.layout.recycler_item_friend_room, parent, false
            )
        )
    }

    override fun onBindViewHolder(holder: RecyclerViewHolder, position: Int) {

        val view: View = holder.itemView
        view.tv_name.text = rooms[position].nickname
        view.setOnClickListener { v ->
            mOnClickItemListener!!.onClickItem(v, position)
        }
        view.tag = position
    }

    override fun getItemCount(): Int {
        return rooms.size
    }

    fun addData(rooms: MutableList<FriendOrRoom>) {
        this.rooms.clear()
        this.rooms.addAll(rooms)
        this.notifyDataSetChanged()
    }


    /**
     * 添加条目
     * */
    fun addDataItem(room: FriendOrRoom) {
        this.rooms.add(itemCount, room)
        this.notifyItemChanged(itemCount)
    }

    /**
     * 移除条目
     * */
    fun removeDataItem(friend: FriendOrRoom) {
        for ((index, value) in this.rooms.withIndex()) if (value.id == friend.id) {
            this.rooms.removeAt(index)
            this.notifyItemRangeRemoved(index, itemCount + 1)
            return
        }
    }

    interface OnClickItemListener {
        fun onClickItem(view: View, position: Int)
    }
}
